package cn.circle.system.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.circle.system.util.DataGrid;
import cn.circle.system.util.PageHelper;
import cn.circle.system.dao.ISysCustomerDao;
import com.graduation.system.model.SysCustomer;
import cn.circle.system.service.ISysCustomerService;
import cn.circle.system.util.HqlHelper;

@Repository
public class SysCustomerService implements ISysCustomerService{

	@Autowired
	public ISysCustomerDao sysCustomerDao;
	
	DataGrid dg = new DataGrid();
	
	public DataGrid datagrid(PageHelper ph, SysCustomer c ,String depId,String userName) {

		DataGrid dg = new DataGrid();
		List<SysCustomer> cml = new ArrayList<SysCustomer>();
		// 用来放置查询的条件
		Map<String, Object> params = new HashMap<String, Object>();
		// 注意下面为HQL语句，里面sql的关键字大小写不敏感，其它是敏感的,from后面是model类名称
		StringBuffer hql = new StringBuffer("from SysCustomer t where 1=1 ");
		// 以下为查询条件
		if (null != depId && Integer.parseInt(depId) != 0) {
			System.out.println(depId);
			params.put("depId", Integer.parseInt(depId));
			hql.append(" and t.sysDepartment.depId = :depId ");
		}
		if (userName != null && !"".equals(userName)) {
			System.out.println(userName);
			String custName = null;
			try {
				custName = URLDecoder.decode(c.getUserName(), "GBK");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			params.put("userName", "%" + custName + "%");
			hql.append(" and t.userName like :userName ");
		}
		hql = HqlHelper.orderHql(hql, ph); // 排序
		List<SysCustomer> l = sysCustomerDao.find(hql.toString(), params, ph.getPage(), ph.getRows());
		dg.setRows(l);
		dg.setTotal(sysCustomerDao.count("select count(*) " + hql, params));
		return dg;
	}

	public List<SysCustomer> getUser(String id) {
		// TODO Auto-generated method stub
		return sysCustomerDao.getUser(id);
	}
	public boolean save(SysCustomer sysCustomer) {
	//	SessionFactory sessionFactory 
		sysCustomerDao.save(sysCustomer);
		return true;
		

	}

	public boolean update(SysCustomer c) {
		// TODO Auto-generated method stub
		sysCustomerDao.updataAll(c);
		return true;
	}

	@Override
	public boolean delete(String custIds) {
		// TODO Auto-generated method stub
		return sysCustomerDao.deleteAll(custIds);
	}

}
